package com.zby.model.pojo;
import com.zby.model.pojo.User; // 假设这是你的用户实体类
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.Collections;

@Data
public class CustomUserDetails implements UserDetails {

    // 基础字段
    // 用户ID（核心业务标识）
    private Integer id;
    // 登录名（唯一）
    private String username;
    // 加密后的密码
    private String password;

    // 扩展字段（根据业务需求添加）
    // 邮箱
    private String email;
    // 头像地址
    private String avatarUrl;
    // 手机号
    private String phone;

    // 权限信息
    private Collection<? extends GrantedAuthority> authorities;

    // 账户状态（默认启用）
    private boolean enabled = true;
    private boolean accountNonExpired = true;
    private boolean credentialsNonExpired = true;
    private boolean accountNonLocked = true;

    /**
     * 从数据库用户实体转换
     * @param user 数据库中的用户实体
     */
    public CustomUserDetails(User user) {
        this.id = user.getId();
        this.username = user.getUsername();
        this.password = user.getPassword();
        this.email = user.getEmail();
        this.avatarUrl = user.getAvatar();
        // 转换权限（示例：角色以ROLE_开头）
        this.authorities = Collections.singletonList(
                new SimpleGrantedAuthority("ROLE_" + user.getRole())
        );
    }

    // 必须实现的 UserDetails 方法
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return accountNonExpired;
    }

    @Override
    public boolean isAccountNonLocked() {
        return accountNonLocked;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return credentialsNonExpired;
    }

    @Override
    public boolean isEnabled() {
        return enabled;
    }
}
